package com.tongda.menu.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.tongda.core.common.Constants;
import com.tongda.core.utils.CommunicationUtil;
import com.tongda.menu.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class UpdateVersionHelper {

	private static final String TAG = "UpdateVersionHelper";

	public String UPDATE_SERVER = Constants.BASE_SERVIER_URL + "static/apk/";
	public static String UPDATE_APKNAME = "*.apk";
	public static final String UPDATE_SAVENAME = "canyin-menu-newest.apk";

	public static int getVersionCode(Context context) {
		int versionCode = -1;
		try {
			versionCode = context.getPackageManager().getPackageInfo(Constants.MENU_PACKAGE_STR, 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return versionCode;
	}

	public static String getVersionName(Context context) {
		String versionName = "";
		try {
			versionName = context.getPackageManager().getPackageInfo(Constants.MENU_PACKAGE_STR, 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return versionName;

	}

	public static String getAppName(Context context) {
		String appName = context.getResources().getText(R.string.app_name).toString();
		return appName;
	}

	public UpdateVersionHelper(Activity activity) {
		super();
		this.activity = activity;
	}

	Activity activity;
	public ProgressDialog progressDialog;
	private long fileLength;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.setMax((int) fileLength);
		}

	};

	private int newVersionCode = 0;
	private String newVersionName = "";
	
	public void startProcessOnStart() {
		if (getServerSideVersionCode()) {
			int vercode = getVersionCode(activity);
			if (newVersionCode > vercode) {
				doUpdateVersion();
			}
		}

	}

	public void startProcess() {
		if (getServerSideVersionCode()) {
			int vercode = getVersionCode(activity);
			if (newVersionCode > vercode) {
				doUpdateVersion();
			} else {
				doNotUpdateVersion();
			}
		}
	}

	/**
	 * 获取服务器端版本信息
	 * 
	 * @return
	 */
	private String verjson;
	public boolean getServerSideVersionCode() {
		try {
			Thread subThead = new Thread(new Runnable() {
				
				@Override
				public void run() {
					 verjson = CommunicationUtil.get(Constants.BASE_SERVIER_URL + "mobile/index/updateMenuVersion");
				}
			});
			subThead.start();
			subThead.join();
			JSONObject root = new JSONObject(verjson);
			if (root != null) {
				try {
					newVersionCode = Integer.parseInt(root.getString("versionCode"));
					newVersionName = root.getString("versionName");
					UPDATE_APKNAME = root.getString("apkName");
				} catch (Exception e) {
					newVersionCode = -1;
					newVersionName = "";
					return false;
				}
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 不需要更新版本
	 */
	public void doNotUpdateVersion() {
		String verName = getVersionName(activity);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本:");
		sb.append(verName);
		sb.append(",\n已是最新版,无需更新!");
		Dialog dialog = new AlertDialog.Builder(activity).setTitle("软件版本更新").setMessage(sb.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).create();
		dialog.show();
	}

	/**
	 * 显示更新版本对话框
	 */
	public void doUpdateVersion() {
//		int verCode = getVersionCode(activity);
		String verName = getVersionName(activity);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本:");
		sb.append(verName);
		// sb.append(" Code:");
		// sb.append(verCode);
		sb.append(", 发现新版本:");
		sb.append(newVersionName);
		// sb.append(" Code:");
		// sb.append(newVersionCode);
		sb.append(", 是否更新?");
		Dialog dialog = new AlertDialog.Builder(activity).setTitle("软件更新").setMessage(sb.toString()).setPositiveButton("更新", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				startUpdateTask();
			}

		}).setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		}).create();
		dialog.show();
	}

	protected void startUpdateTask() {
		progressDialog = new ProgressDialog(activity);
		progressDialog.setTitle("正在下载新版本");
		progressDialog.setMessage("下载需要一段时间，请您耐心等待...");
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		new DownloadFileTask().execute(UPDATE_SERVER + UPDATE_APKNAME);
	
	}

	void installNewVersion() {

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Constants.FILE_BASE_PATH, UPDATE_SAVENAME)), "application/vnd.android.package-archive");
		activity.startActivity(intent);
	}

	/**
	 * 文件下载任务
	 * 
	 * @author andy
	 * 
	 */
	private class DownloadFileTask extends AsyncTask<String, Integer, Message> {

		@Override
		protected Message doInBackground(String... params) {
			publishProgress(1);
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(params[0]);
			try {  
				HttpResponse response = client.execute(get);
				HttpEntity entity = response.getEntity();
				fileLength = entity.getContentLength();
				handler.sendEmptyMessage(0);
				InputStream is = entity.getContent();
				FileOutputStream fileOutputStream = null;
				if (is != null) {
					File fileDir = new File(Constants.FILE_BASE_PATH);
					if(!fileDir.exists()){
						fileDir.mkdir();
					}
					 File file = new File(fileDir,UPDATE_SAVENAME);
					try {
						fileOutputStream = new FileOutputStream(file);
					} catch (Exception e) {
						Log.e("UpdateVersionException", e.toString());
					}
				
					
					byte[] buf = new byte[1024];
					int ch = -1;
					int count = 0;
					while ((ch = is.read(buf)) != -1) {
						fileOutputStream.write(buf, 0, ch);
						count += ch;
						publishProgress(count);
						if (fileLength > 0) {
						}
					}

				}
				fileOutputStream.flush();
				if (fileOutputStream != null) {
					fileOutputStream.close();
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				Log.i("Exception", e.toString());
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Message result) {
			super.onPostExecute(result);
			progressDialog.cancel();
			installNewVersion();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
					progressDialog.setProgress(values[0]);
					Log.i("URL", UPDATE_SERVER + UPDATE_APKNAME);
		}

	}

}